package org.streets.eis.ext.rbac.entities;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

import org.apache.wicket.util.string.Strings;
import org.streets.database.annotations.NestedFetch;
import org.streets.eis.component.model.ListItem;
import org.streets.eis.entity.Position;
import org.streets.eis.entity.User;


@Entity
@Table(name="eis_employee")
public class Employee4Rbac implements Serializable {		
	private static final long serialVersionUID = 1L;
	
	@Id
	public String id;
	
	@Column
	public String name;
	
	@Column
	public String userId;
	
	@Column
	public String posId;
	
	@NestedFetch(type=User.class, value="select * from eis_user where user_id = :userId")
	public User user;
	
	@NestedFetch(type=Position.class, value="select * from eis_position where id = :posId")
	public Position position;
	
	public Employee4Rbac() {
	}

	public Integer getUserLevel(){
		return user!=null ? user.getLevel() : null;
	}
	
	public void setUserLevel(Integer level){
		if (user==null) user = newUser();
		user.setLevel(level);
	}
	
	public ListItem getPosition(){
		return position==null? new ListItem("","") : new ListItem(position.getId(),position.getName());
	}
	
	private User newUser(){
		User tmp = new User();
		tmp.setUid("");
		return tmp;
	}
	
	private Position newPosition(){
		Position tmp = new Position();
		tmp.setId("");
		return tmp;
	}
	
	public void setPosition(ListItem item){
		if (position==null){
			position = newPosition();
		}
		position.setId(item.getId());
		position.setName(item.getText());
	}
	
	public String getPassword(){
		return Strings.isEmpty(userId) ? ""  : "********************************";
	}
	
	public String getEditedPassword(){
		return user!=null ? user.getPasswd() : "";
	}
	
	public void setEditedPassword(String passwd){
		if (user==null) user = newUser();
		user.setPasswd(passwd);
	}
	
	@Override
	public int hashCode(){
		return id.hashCode();
	}
	
	@Override
	public boolean equals(Object obj){
		return obj!=null&&(obj instanceof Employee4Rbac)&&id.equals(((Employee4Rbac)obj).id);
	}
	
}
